﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using SyCODE.Component;
using SyCODE.Component.Security;
using System.IO;
using System.Xml;
using System.Collections;

namespace SyCODE.Blog.Topic
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class HandlerBase : IHttpHandler
    {
        private int MAX_SUMMARY_LEN = 1000;

        public virtual bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public abstract void ProcessRequest(HttpContext context);

        protected virtual string ParseNonPicSummary(string summary)
        {
            summary = Regex.Replace(summary, @"\[img\](.*)\[/img\]", "$1", RegexOptions.IgnoreCase);
            summary = Regex.Replace(summary, @"\s", "");
            return summary;
        }
        /// <summary>
        /// 生成摘要信息
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string ParseSummary(string html)
        {
            string summary = Regex.Replace(html, @"[\r\n]", "");
            summary = Regex.Replace(summary, @">\s*<", "><");
            summary = Regex.Replace(summary, @"<(p|/p)[^>]*>", "\n\n", RegexOptions.IgnoreCase);
            summary = Regex.Replace(summary, @"</div[^>]*><div[^>]*>", "\n", RegexOptions.IgnoreCase);
            summary = Regex.Replace(summary, @"</li[^>]*><li[^>]*>", "\n&nbsp;&nbsp;·", RegexOptions.IgnoreCase);
            summary = Regex.Replace(summary, @"<li[^>]*>", "\n&nbsp;&nbsp;·", RegexOptions.IgnoreCase);
            summary = Regex.Replace(summary, @"<(div|/div|ul|/ul|ol|/ol|/li|br)[^>]*>", "\n", RegexOptions.IgnoreCase);

            summary = Regex.Replace(summary, @"<img.*[\s|/]+src=\s*('|"")+([^(\1|"")]+)(?=\1)[^>]*>", "\n[img]$2[/img]\n");
            summary = Regex.Replace(summary, @"<img.*[\s|/]+src=\s*([^(\s|"")]+)[^>]*>", "\n[img]$1[/img]\n");

            summary = Regex.Replace(summary, @"<[^>]*>", "");
            summary = Regex.Replace(summary, @"[\f\t\v]{2,}", " ");
            summary = Regex.Replace(summary, @"&nbsp;", " ");
            summary = Regex.Replace(summary, @"[\r\n]{3,}", "\n\n");

            summary = HttpUtility.HtmlDecode(summary.Trim());
            summary = Regex.Replace(summary, @"[\u0000-\u0008\u000B\u000C\u000E-\u001A\uD800-\uDFFF]", "");
            summary = Function.StringCut(summary, MAX_SUMMARY_LEN);
            summary = Regex.Replace(summary, @"\[img\][^\]]*$", "");
            return summary;
        }

        /// <summary>
        /// 检测文章内容
        /// </summary>
        /// <param name="nvc">文章内容信息的键值集合</param>
        /// <returns></returns>
        protected virtual bool CheckInfo(string form, NameValueCollection nvc)
        {
            if (nvc["title"].Trim().Length == 0)
            {
                Function.ClientAlert(StringResource.GetField("mustinputtopictitle"));
                return false;
            }
            else
            {
                nvc.Set("content", Function.DangerTagsFilter(nvc["content"]));

                string summary = String.Empty;
                if ((summary = ParseSummary(nvc["content"])).Length == 0)
                {
                    Function.ClientAlert(StringResource.GetField("mustinputtopiccontent"));
                    return false;
                }
                if (nvc["summary"].Trim().Length == 0)
                {
                    nvc.Set("summary", summary);
                }

                if (String.IsNullOrEmpty(nvc["hometop"]))
                {
                    nvc.Add("hometop", "false");
                }
                if (String.IsNullOrEmpty(nvc["sorttop"]))
                {
                    nvc.Add("sorttop", "false");
                }

                string[] tags = Regex.Replace(nvc["tags"], @"[^\w|\s|,]", "").Trim().Split(' ');
                Array.Sort(tags);

                nvc.Set("tags", String.Join(" ", tags));

                return true;
            }
        }

        protected virtual void WriteStore(string bloger)
        {
            string storePath = Path.Combine(AppPath.GetUserPhysicalPath(bloger), "store.xml");
            XmlDocument store = new XmlDocument();
            store.Load(storePath);

            string year = DateTime.Now.Year.ToString();
            string month = DateTime.Now.Month.ToString();
            int day = DateTime.Now.Day;

            XmlElement monthNode = (XmlElement)store.DocumentElement.SelectSingleNode(String.Format("body/a[@id='{0}' and @name='{1}']", year, month));
            char[] idx;
            if (monthNode != null)
            {
                int count = Int32.Parse(monthNode.InnerText) + 1;
                monthNode.InnerText = count.ToString();
                idx = monthNode.GetAttribute("index").ToCharArray();
            }
            else
            {
                monthNode = store.CreateElement("a");
                monthNode.SetAttribute("id", year);
                monthNode.SetAttribute("name", month);
                monthNode.SetAttribute("href", String.Format("store/{1}/{2}.xml", bloger, year, month));
                monthNode.InnerText = "1";
                store.DocumentElement.LastChild.AppendChild(monthNode);
                idx = "0000000000000000000000000000000".ToCharArray();
            }
            idx[day - 1] = '1';
            monthNode.SetAttribute("index", new String(idx));

            store.Save(storePath);
        }

        protected virtual void WriteLast4(string bloger, string id, string title)
        {
            //更新最后4篇日志的静态XML存档文件
            string last4Path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), "last4.xml");

            XmlDocument last4Dom = new XmlDocument();
            last4Dom.Load(last4Path);

            XmlElement last4topic = last4Dom.CreateElement("a");

            last4topic.SetAttribute("id", id);
            last4topic.InnerText = title;
            last4Dom.DocumentElement.AppendChild(last4topic);

            //如果存档里的最新评论数量超过4条则删除最早写入的一篇日志的联接
            if (last4Dom.DocumentElement.ChildNodes.Count > 4)
            {
                last4Dom.DocumentElement.RemoveChild(last4Dom.DocumentElement.FirstChild);
            }

            last4Dom.Save(last4Path);
        }

        protected virtual void UpdateLast4(string bloger, string id, string title)
        {
            //更新最后4篇日志的静态XML存档文件
            string last4Path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), "last4.xml");

            XmlDocument last4Dom = new XmlDocument();
            last4Dom.Load(last4Path);

            XmlElement last4topic = (XmlElement)last4Dom.DocumentElement.SelectSingleNode("a[@id='" + id + "']");
            if (last4topic != null)
            {
                last4topic.InnerText = title;
                last4Dom.DocumentElement.AppendChild(last4topic);
            }
            else
            {
                last4topic = last4Dom.CreateElement("a");

                last4topic.SetAttribute("id", id);
                last4topic.InnerText = title;
                last4Dom.DocumentElement.AppendChild(last4topic);

                //如果存档里的最新评论数量超过4条则删除最早写入的一篇日志的联接
                if (last4Dom.DocumentElement.ChildNodes.Count > 4)
                {
                    last4Dom.DocumentElement.RemoveChild(last4Dom.DocumentElement.FirstChild);
                }
            }

            last4Dom.Save(last4Path);
        }

        protected virtual string[] FormatTags(string tagstr)
        {
            string[] tags = tagstr.Split(new char[] { ',', ' ', '/' }, StringSplitOptions.RemoveEmptyEntries);
            Array.Sort<string>(tags);
            ArrayList output = new ArrayList();
            string current = String.Empty;

            for (int i = 0; i < tags.Length; i++)
            {
                string tag = Function.StringCut(Regex.Replace(tags[i], @"[^\w\d\+#]", ""), 10);
                if (tag != current)
                {
                    output.Add(current = tag);
                }
            }

            string[] outTags = new string[Math.Min(output.Count,6)];
            output.CopyTo(0, outTags, 0, outTags.Length);

            return outTags;
        }
    }
}